package org.batatasframework.support.event.internal;

import org.batatasframework.support.database.AliasGenerator;
import org.batatasframework.support.database.IdentifyTableGenerator;
import org.batatasframework.support.database.jdbc.ConnectionAccessor;
import org.batatasframework.support.database.metadatas.TableMetadata;
import org.batatasframework.support.database.sql.field.SelectFragment;
import org.batatasframework.support.event.SearchableRequest;
import org.batatasframework.support.searchable.SearchableInputStream;
import org.batatasframework.support.searchable.result.GroupResultBuffer;
import org.batatasframework.support.searchable.result.SearchResultBuffer;
import org.batatasframework.support.searchable.result.StatisticsResultBuffer;

import cn.bonoon.kernel.support.IOperator;

public abstract class AbstractSearchableRequest<T extends TableMetadata> implements SearchableRequest{
	
	/** 暂时使用这个接口，以后会改为其它更中性、更通用的接口 */
	protected final IOperator operator;
	
	protected ConnectionAccessor connectionAccessor;
	
	protected T sourceTableMetadata;
	protected AliasGenerator aliasGenerator = new AliasGenerator();
	/** 生成实际需要访问的表，如果是写的方式呢？ */
	protected IdentifyTableGenerator tableObjectGenerator;
	
	protected SearchableInputStream inputStream;
	
	protected AbstractSearchableRequest(IOperator operator){
		this.operator = operator;
	}
	
	@Override
	public SearchableInputStream getInputStream() {
		if(null == inputStream) return new SearchResultBuffer();
		return inputStream;
	}
	
	@Override
	public void setInputStream(SearchableInputStream inputStream) {
		this.inputStream = inputStream;
	}
	
	@Override
	public TableMetadata getTableMetadata() {
		return sourceTableMetadata.getTableMetadata();
	}
	
	public IdentifyTableGenerator getTableObjectGenerator() {
		return tableObjectGenerator;
	}

	public void setTableObjectGenerator(IdentifyTableGenerator tableObjectGenerator) {
		this.tableObjectGenerator = tableObjectGenerator;
	}

	public AliasGenerator getAliasGenerator() {
		return aliasGenerator;
	}

	public void setAliasGenerator(AliasGenerator aliasGenerator) {
		this.aliasGenerator = aliasGenerator;
	}

	public IOperator getOperator() {
		return operator;
	}

	public ConnectionAccessor getConnectionAccessor() {
		return connectionAccessor;
	}

	public void setConnectionAccessor(ConnectionAccessor connectionAccessor) {
		this.connectionAccessor = connectionAccessor;
	}

	public SearchableInputStream buildInputStream(SelectFragment groupFragment, boolean asStatisitics) throws Exception {
		if(null != groupFragment){
			if(asStatisitics){
				return new StatisticsResultBuffer(groupFragment);
			}else{
				return new GroupResultBuffer(groupFragment);
			}
		}else{
			return new SearchResultBuffer();
		}
	}
	
}
